<template>
  <div>
    <!-- 1．输入着name属性“用户名"
        表单整体提交时，默认收集一个提交对象
        往后台发送的参数名就是name里值
        {"用户名":‘页面值号} -->
    <van-nav-bar title="极客园-登录" />
    <van-form @submit="onSubmit">
      <van-field
        v-model="user.mobile"
        required
        name="mobile"
        label="手机号"
        placeholder="请输入11位手机号"
        :rules="[{ required: true, message: '请正确填写手机号', pattern: /^1[3-9]\d{9}$/ }]"
      />
      <van-field
        v-model="user.code"
        required
        type="password"
        name="code"
        label="密码"
        placeholder="请输入6位密码"
        :rules="[{ required: true, message: '请填写密码', pattern: /^\d{6}$/ }]"
      />
      <div style="margin: 16px">
        <van-button
          :loading="isLoading"
          :disabled="isLoading"
          loading-text="登录中..."
          round
          block
          type="info"
          native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { loginAPI } from '@/api/index.js'
import { setToken } from '@/utils/token.js'
// 函数调用
import { Notify } from 'vant'
export default {
  data() {
    return {
      user: {
        mobile: '13776268059',
        // 验证码必须是246810，后台做了判断
        code: '246810'
      },
      isLoading: false
    }
  },
  methods: {
    async onSubmit(values) {
      this.isLoading = true
      try {
        const res = await loginAPI(values)
        Notify({ type: 'success', message: '登陆成功！', duration: 1000 })
        // 在本地保存refreshToken
        window.localStorage.setItem('refreshToken', res.data.data.refresh_token)
        setToken(res.data.data.token)
        // 跳转要写在最后，尽量最后执行
        // this.$router.replace(this.$store.state.routerUrl)
        console.log(this.$route)
        this.$router.replace(this.$route.query.path || '/layout/home')
      } catch (err) {
        Notify({ type: 'danger', message: '手机号或者密码出错！', duration: 1000 })
      }
      // 网络请求完成无论成功/报错,把状态关掉
      this.isLoading = false
    }
  }
}
</script>

<style></style>
